var nspi = require("@native.spi");
var sys = require("@native.builtin");

MODE_SLAVE = 0;
MODE_MASTER = 1;

POLARITY_LOW = 0;
POLARITY_HIGH = 1;

PHASE_1EDGE = 0;
PHASE_2EDGE = 1;

FIRSTBITS_LSB = 0;
FIRSTBITS_MSB = 1;

function SPI(id) {
    this.id = id;

    this.write = function(buffer){
        if(buffer == undefined)
            return undefined;

        if(buffer == undefined || buffer.length == 0)
            return undefined;
        var size = buffer.length;
        var data = sys.malloc(size);
        if(data == null)
            return undefined;
        sys.copy(data, buffer, size);
        nspi.write(this.id, data, size);
        sys.free(data);
    }

    this.read = function(num){
        if(num == undefined || num == 0 || typeof(num) != "number")
            return undefined;
        var buffer = sys.malloc(num);
        if(buffer == null)
            return undefined;
        var ret = nspi.read(this.id, buffer, num);
        if(ret == 0){
            sys.free(buffer);
            return sys.toJsArray(buffer, num);
        }
        sys.free(buffer);
        return undefined;
    }

    this.close = function(){
        nspi.close(this.id);
    }
}

function open(opt){
    if(opt == undefined)
        return undefined;
    
    var id = opt["id"];
    var mode = opt["mode"];
    var freq = opt["freq"];
    if (id == undefined || mode == undefined || freq == undefined)
        return undefined;

    if (
        typeof id != "number" ||
        typeof mode != "number" ||
        typeof freq != "number"
    )
        return undefined;

    var polarity = opt["polarity"];
    if (polarity == undefined || typeof polarity != "number")
        polarity = POLARITY_LOW;
    var phase = opt["phase"];
    if (phase == undefined || typeof phase != "number") phase = PHASE_1EDGE;
    var firstbit = opt["firstbit"];
    if (firstbit == undefined || typeof firstbit != "number")
        firstbit = FIRSTBITS_LSB;

    if(nspi.open(id, mode, freq, polarity, phase, firstbit) == 0)
        return new SPI(id);
    return undefined;
}
